package com.example.juccode.juc02completableFuture.demo;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author: zhongkui 1365693530@qq.com
 * @Date: 2025/2/12
 */
public class CompletableFutureApiDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {

        /**
         * 获得结果和触发运算
         */
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "hello-supplyAsync";
        });
        //不见不散
//        System.out.println(completableFuture.get());
        //过时不候
//        System.out.println(completableFuture.get(2, TimeUnit.SECONDS));
        //和get一样 不抛异常
//        System.out.println(completableFuture.join());
        //调用该方法时，如果计算完成，则返回计算结果，如果未完成，则返回默认值。
//        System.out.println(completableFuture.getNow("hello"));
        try {TimeUnit.SECONDS.sleep(2);} catch (Exception e) {e.printStackTrace();}
        System.out.println(completableFuture.complete("completeValue") + "\t" + completableFuture.join() );
    }
}
